package com.fuchuang.seckillsystem.redis;

import com.fuchuang.seckillsystem.dto.KeyConstants;
import com.fuchuang.seckillsystem.entity.Goods;
import com.fuchuang.seckillsystem.mapper.GoodsMapper;
import com.fuchuang.seckillsystem.service.ISeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 监听所有db的过期事件"
 */

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    
    @Autowired
    private ISeckillService seckillService;
    
    @Resource
    private GoodsMapper goodsMapper;
    
    
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    
    /**
     * 由于rocketmq的延迟队列不能自定义过期时间，故采用redis的key监听
     * 针对redis数据失效事件，进行数据处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //用message.toString()可以获取失效的key
        String expiredKey = message.toString();
        if (expiredKey.startsWith(KeyConstants.SECKILL_ACTIVITY)) {
            //如果是秒杀活动过期
            Integer activityId = getIdFromKey(expiredKey);
            log.info("活动：" + activityId + "过期！");
            //移除isEmpty中秒杀活动商品数据
            List<Goods> goods = goodsMapper.queryGoodsByActivityId(activityId);
            List<Integer> goodsIds = new ArrayList<>();
            for (Goods g : goods) {
                goodsIds.add(g.getId());
            }
            seckillService.removeGoodsFromIsEmpty(goodsIds, activityId);
        }
    }
    
    private Integer getIdFromKey(String expiredKey) {
        return Integer.valueOf(expiredKey.substring(expiredKey.lastIndexOf(":") + 1));
    }
}